<template>
  <div class="role">
    <h5>角色管理</h5>
    <el-button
      type="primary"
      icon="el-icon-plus"
      class="addBtn"
      @click="addClick"
      >新增</el-button
    >
    <el-table
      :data="state.tableData"
      style="width: 100%"
      size="medium"
      :header-row-style="{ color: 'rgba(0,0,0,.7)' }"
    >
      <el-table-column prop="id" label="角色ID" width="180"> </el-table-column>
      <el-table-column prop="name" label="角色名称" width="180">
      </el-table-column>
      <el-table-column prop="pid" label="排序"> </el-table-column>
      <el-table-column prop="createtime" label="添加时间"> </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <template v-if="scope.row.id > 1">
            <span class="edit-btn btn" @click="editClick(scope.index_)"
              >编辑</span
            >
            <span class="btn" @click="delPrompt(scope.row.id)">删除</span>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      title="编辑角色"
      v-model="state.dialogVisible"
      custom-class="dialog"
      :append-to-body="true"
      @close="closeDialog"
    >
      <el-form
        :model="state.form"
        label-width="80px"
        hide-required-asterisk
        class="form"
      >
        <el-form-item label="角色名称:" required>
          <el-input v-model="state.form.name" autocomplete="off"></el-input>
        </el-form-item>

        <!-- <el-form-item label="上级角色:">
          <el-select v-model="state.form.region" placeholder="请选择角色">
            <el-option :label="item.name" :value="item.pid" v-for="item in state.tableData" :key="item.id"></el-option>
          </el-select>
        </el-form-item> -->
        <div class="tree">
          <div class="title">菜单权限:</div>
          <div class="tree-list">
            <el-tree
              :data="state.newPowerData"
              show-checkbox
              node-key="id"
              :default-expanded-keys="state.defaultExpandedKeys"
              :default-checked-keys="state.defaultCheckedKeys"
              :props="state.defaultProps"
              ref="tree"
            >
            </el-tree>
            <div class="info">设置该角色有权操作的功能</div>
          </div>
        </div>

        <!-- <el-form-item label="排序:" required>
          <el-input v-model="state.form.sott" autocomplete="off"></el-input>
        </el-form-item> -->
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="state.dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="comfirmBtn">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { reactive, onMounted, getCurrentInstance } from "vue";
import { ElMessage, ElLoading, ElMessageBox } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import { dateFormat } from "@/utils/validate.js";
const state = reactive({
  tableData: [],
  powerData: [],
  newPowerData: [],
  group_id: -1,
  dialogVisible: false,
  isEdit: false,
  defaultExpandedKeys: [],
  defaultCheckedKeys: [],
  form: {
    name: "",
    region: "",
    sort: "",
  },
  selectData: [
    {
      id: 1,
      label: "首页",
      children: [
        {
          id: 4,
          label: "二级 1-1",
          children: [
            {
              id: 9,
              label: "三级 1-1-1",
            },
            {
              id: 10,
              label: "三级 1-1-2",
            },
          ],
        },
      ],
    },
    {
      id: 2,
      label: "管理员",
      children: [
        {
          id: 5,
          label: "二级 2-1",
        },
        {
          id: 6,
          label: "二级 2-2",
        },
      ],
    },
    {
      id: 3,
      label: "设置",
      children: [
        {
          id: 7,
          label: "二级 3-1",
        },
        {
          id: 8,
          label: "二级 3-2",
        },
      ],
    },
  ],
  defaultProps: {
    children: "children",
    label: "title",
  },
});

export default {
  name: "Role",
  components: {},
  setup(props, { emit }) {
    const { ctx, proxy } = getCurrentInstance();
    const th = getCurrentInstance();
    const _this = th.appContext.config.globalProperties;
    //获取分组列表
    const getRoleList = () => {
      _this
        .$request({
          url: "?s=Learn.Admin.GetGroups",
          params: {
            page: 1,
            pageSize: 10,
          },
        })
        .then((res) => {
          if (res.ret == 200) {
            state.tableData = res.data.data.map((e) => {
              e.createtime = dateFormat(new Date(e.createtime));
              return e;
            });
          }
        });
    };
    //获取权限列表
    const getMenuList = () => {
      _this
        .$request({
          url: "?s=Learn.Admin.AdminRoles",
          params: {
            page: 1,
            pageSize: 10,
          },
        })
        .then((res) => {
          if (res.ret == 200) {
            let powerData = res.data.admin_roles;
            let newPowerData = [];
            for (const key in powerData) {
              newPowerData.push(powerData[key]);
            }
            state.newPowerData = newPowerData;
          }
        });
    };
    // 添加按钮
    function addClick() {
      state.isEdit = false;
      state.form.name = "";
      state.defaultCheckedKeys = [];
      state.dialogVisible = true;
    }
    //添加请求接口
    const addGroup = (data) => {
      _this
        .$request({
          url: "?s=Learn.Admin.addgroup",
          data,
        })
        .then((res) => {
          if (res.ret == 200) {
            ElMessage.success({
              message: "添加成功",
              type: "success",
            });
            state.form.name = "";
            getRoleList();
            state.dialogVisible = false;
          }
        });
    };
    //点击编辑按钮
    function editClick(index) {
      state.group_id = state.tableData[index].id;
      editDetail(state.group_id);
      state.isEdit = true;
      state.dialogVisible = true;
    }
    //获取编辑详情
    const editDetail = (group_id) => {
      _this
        .$request({
          url: "?s=Learn.Admin.group_row",
          params: {
            group_id,
          },
        })
        .then((res) => {
          if (res.ret == 200) {
            state.form.name = res.data.group.name;
            console.log(res.data.group.rules.split(","));
            state.defaultCheckedKeys = res.data.group.rules.split(",");
          }
        });
    };
    //编辑请求接口
    const editGroup = (data) => {
      _this
        .$request({
          url: "?s=Learn.Admin.editgroup",
          data,
        })
        .then((res) => {
          if (res.ret == 200) {
            ElMessage.success({
              message: "编辑成功",
              type: "success",
            });
            state.form.name = "";
            getRoleList();
            state.dialogVisible = false;
          }
        });
    };
    //删除接口
    const delGroup = (group_id) => {
      _this
        .$request({
          url: "?s=Learn.Admin.group_del",
          params: {
            group_id,
          },
        })
        .then((res) => {
          if (res.ret == 200) {
            ElMessage.success({
              message: "删除成功",
            });
            getRoleList()
          } else {
            ElMessage.error({
              message: res.msg,
            });
          }
        });
    };
    //关闭dialog
    const closeDialog = () => {
      state.isEdit = false;
      state.defaultCheckedKeys = [];
    };
    //遍历data转换formdata
    function changeData(data) {
      let formData = new FormData();
      for (const key in data) {
        formData.append(key, data[key]);
      }
      return formData;
    }
    //确认按钮
    const comfirmBtn = () => {
      let rules = proxy.$refs.tree.getCheckedKeys();
      if (state.form.name == "") {
        ElMessage.success({
          message: "请输入姓名",
          type: "fail",
        });
        return;
      }
      let oldData = { name: state.form.name, rules: rules };
      if (state.isEdit) {
        oldData.group_id = state.group_id;
      }
      let data = changeData(oldData);

      if (state.isEdit) {
        editGroup(data);
      } else {
        addGroup(data);
      }
    };
    //删除按钮
    const delPrompt = (id) => {
      ElMessageBox.confirm("确认后将无法恢复", "您确定要删除该记录吗?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delGroup(id);
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "已取消删除",
          });
        });
    };
    onMounted(() => {
      getRoleList();
      getMenuList();
    });
    return {
      state,
      closeDialog,
      getMenuList,
      editClick,
      comfirmBtn,
      addClick,
      addGroup,
      delGroup,
      editDetail,
      delPrompt,
    };
  },
};
</script>
<style lang="scss" scoped>
.role {
  background: #ffffff;
  h5 {
    font-size: 16px;
    padding: 20px 56px;
    border-bottom: 1px solid #e9e9e9ff;
  }
  .addBtn {
    margin-left: 56px;
    margin-bottom: 20px;
  }
  .btn {
    color: #1890ff;
    cursor: pointer;
  }
  .edit-btn {
    margin-right: 8px;
  }
  .tree {
    display: flex;
    .title {
      padding-right: 10px;
      margin-left: 10px;
    }
  }
  /deep/ .el-table {
    th {
      background: #fafafa;
      padding: 16px 0;
      text-align: center;
    }
  }
  /deep/ .el-table {
    td {
      padding: 16px 0;
      text-align: center;
    }
  }
}
</style>
<style lang="scss">
.el-overlay {
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1;
  .el-form {
    width: 50%;
    margin: 0 auto;
    .el-select {
      width: 100%;
    }
  }
  .tree {
    display: flex;
    margin: 24px 0;
    .title {
      padding-right: 10px;
      margin-left: 14px;
    }
    .info {
      clear: both;
      min-height: 22px;
      color: rgba(0, 0, 0, 0.45);
      font-size: 13px;
      margin-top: 10px;
    }
  }
}
</style>
